<template>
  <div>
    <el-dialog
      v-model="visible"
      title="新建"
      class="add-vpc-route-config-dialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="configRules"
        class="m-auto mt-1"
      >
        <el-form-item label="IP地址/掩码" prop="ipv4">
          <el-input v-model="form.ipv4" placeholder="请按照0.0.0.0/0格式填写" />
        </el-form-item>
        <el-form-item label="下一跳类型" prop="type">
          <el-radio-group v-model.number="form.type">
            <el-radio-button label="下一跳地址" :value="2" />
            <el-radio-button label="出接口" :value="1" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="下一跳" prop="next">
          <el-input v-model="form.next" v-if="form.type === 2" />
          <el-select
            filterable
            clearable
            v-model="form.next"
            class="w-full"
            v-else
          >
            <el-option
              v-for="item in portList"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="距离" prop="metric">
          <el-input v-model="form.metric" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="addRouterConfigData">
            新 建
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onUnmounted } from 'vue';
import { verifyIP } from '@/utils/common';
import { ElMessage } from 'element-plus';
import { addRouterConfigByVPCApi } from '@/api/topo/vpc';
import { getPortByVPCApi } from '@/api/topo/vpc';
import { emitter } from '@/utils/bus';

const emit = defineEmits(['updateData']);

// 表单
const visible = ref(false);
const formRef = ref(null);
const form = reactive({
  ipv4: '',
  type: 2,
  next: '',
  metric: '',
});

// 接口列表
const portList = ref([]);

/**
 * 校验IP/掩码格式
 * @param rule
 * @param value
 * @param callback
 * @returns {*}
 */
const validateIP = (rule, value, callback) => {
  if (!value) return callback('IP地址/掩码不能为空');

  const [ip, mask] = value.split('/');
  if (!verifyIP(ip)) return callback('请输入合法IP地址/掩码，格式： 0.0.0.0/0');

  const masks = /^(?:[0-9]|[12]\d|3[0-2])$/;
  if (!masks.test(mask)) {
    return callback('请输入合法IP地址/掩码，掩码范围0-32');
  }
  return callback();
};

// 校验规则
let configRules = {
  ipv4: [{ validator: validateIP, required: true, trigger: 'blur' }],
  next: [{ required: true, message: '下一跳不能为空', trigger: 'blur' }],
  metric: [{ required: true, message: '距离不能为空', trigger: 'blur' }],
};

/**
 * 确认添加路由配置
 */
const addRouterConfigData = () => {
  formRef.value?.validate(async valid => {
    if (valid) {
      addRouterConfigByVPCApi(vpcID.value, form).then(res => {
        if (!(res instanceof Error)) {
          ElMessage.success('新建成功');
          visible.value = false;
          emit('updateData');
        }
      });
    }
  });
};

/**
 * 获取接口列表
 */
const getPortList = () => {
  getPortByVPCApi(vpcID.value).then(res => {
    if (!(res instanceof Error)) {
      // 过滤未生成数据
      if (res.data?.length > 0) {
        portList.value = res.data.filter(item => item.generate);
      }
    }
  });
};

// vpcID
const vpcID = ref(null);
const addRouterConfigFunc = item => {
  visible.value = true;
  vpcID.value = item.vpcID;
};

emitter.on('addRouterConfig', addRouterConfigFunc);

watch(
  visible,
  () => {
    if (!visible.value) {
      formRef.value?.resetFields();
    } else {
      getPortList();
    }
  },
  { immediate: false },
);

onUnmounted(() => {
  emitter.off('addRouterConfig', addRouterConfigFunc);
});
</script>

<style lang="scss" scoped>
:deep(.add-vpc-route-config-dialog) {
  width: 560px;
  .el-form {
    max-width: 460px;
    .el-form-item__label {
      width: 100px;
    }
  }
}
</style>
